﻿using System;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Web.DynamicData;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NotAClue.Web;
using NotAClue.Web.DynamicData;
using NotAClue.ComponentModel.DataAnnotations;

namespace DD_Extensions
{
    public partial class ForeignKeyChangeAware_EditField : ChildChangingAwareFieldTemplate, IChangeNotifyingFieldTemplate //System.Web.DynamicData.FieldTemplateUserControl
    {
        private const string HEADER = "Header";
        private const string SERIES = "Series";
        #region IChangeNotifyingFieldTemplate Members

        public ListItem State
        {
            get { return DropDownList1.SelectedItem; }
        }

        //event ChangingAwareEventHandler IChangeNotifyingFieldTemplate.StateChanged
        //{
        //    add { throw new NotImplementedException(); }
        //    remove { throw new NotImplementedException(); }
        //}
        /// <summary>
        /// publish event.
        /// </summary>
        public event ChangingAwareEventHandler StateChanged;

        /// <summary>
        /// Gets a value indicating whether this instance has events.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance has events; otherwise, <c>false</c>.
        /// </value>
        public new Boolean HasEvents
        {
            get { return StateChanged != null; }
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // make sure we have a handler attached
            if (StateChanged != null)
            {
                //raise event
                StateChanged(this, new ChangingAwareEventArgs(DropDownList1.SelectedItem));
            }
        }
        #endregion

        #region Event
        // added page init to hookup the event handler
        protected void Page_Init(object sender, EventArgs e)
        {
            // add tool-tip
            this.SetupTip();

            // set field options
            this.SetFieldOptions();

            // add CSS from meta data
            this.ApplyCss();

            if (ParentColumns.Count > 0 && ParentControls.Count > 0)
            {
                foreach (var parent in ParentControls)
                {
                    if (parent.Value != null)
                        parent.Value.StateChanged += MyStateChanged;
                }
            }
        }

        // consume event
        protected void MyStateChanged(object sender, ChangingAwareEventArgs e)
        {
            //if (e.ListItem != null)
            //{
            //    if (e.ListItem.Text == HEADER)
            //    {
            //        RequiredFieldValidator1.Enabled = false;
            //        DynamicValidator1.Enabled = false;
            //        this.Visible = false;
            //    }
            //    else if (e.ListItem.Text == SERIES)
            //    {
            //        SetUpValidator(RequiredFieldValidator1);
            //        SetUpValidator(DynamicValidator1);

            //        this.Visible = true;
            //    }
            //}
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (DropDownList1.Items.Count == 0)
            {
                if (Mode == DataBoundControlMode.Insert && Column.IsRequired)
                    DropDownList1.Items.Add(new ListItem("[Select one]", ""));
                else if (Mode == DataBoundControlMode.Insert || !Column.IsRequired)
                    DropDownList1.Items.Add(new ListItem("[Not Set]", ""));

                //PopulateListControl(DropDownList1);
                this.PopulateListControlFiltered(DropDownList1);
            }

            // check to see if column is read only in insert mode
            Column.DisableFieldTemplate(Mode, DropDownList1);
        }

        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);
            string selectedValueString = GetSelectedValueString();
            ListItem item = DropDownList1.Items.FindByValue(selectedValueString);
            if (item != null)
                DropDownList1.SelectedValue = selectedValueString;
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            // set default state
            if (ParentColumns.Count > 0 && ParentControls.Count > 0)
            {
                foreach (var parent in ParentControls)
                {
                    if (parent.Value != null && parent.Value.State != null && parent.Value.State.Text == HEADER)
                    {
                        RequiredFieldValidator1.Enabled = false;
                        DynamicValidator1.Enabled = false;
                        this.Visible = false;
                    }
                    else if (parent.Value != null && parent.Value.State != null && parent.Value.State.Text == SERIES)
                    {
                        SetUpValidator(RequiredFieldValidator1);
                        SetUpValidator(DynamicValidator1);

                        this.Visible = true;
                    }
                }
            }

            // set default values
            if (!IsPostBack && Mode == DataBoundControlMode.Insert)
            {
                var defaultValue = this.GetDefaultValue(Column);
                if (!String.IsNullOrEmpty(defaultValue))
                {
                    // try text and value for default
                    ListItem item = DropDownList1.Items.FindByValue(defaultValue);
                    if (item == null)
                        item = DropDownList1.Items.FindByText(defaultValue);

                    if (item != null)
                        DropDownList1.SelectedValue = item.Value;
                }
            }
        }

        protected override void ExtractValues(IOrderedDictionary dictionary)
        {
            // If it's an empty string, change it to null
            string value = DropDownList1.SelectedValue;
            if (String.IsNullOrEmpty(value))
            {
                value = null;
            }

            ExtractForeignKey(dictionary, value);
        }

        public override Control DataControl
        {
            get { return DropDownList1; }
        }
    }
}
